/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import estg.dae.projecto.bank.controllers.BankSessionLocal;
import estg.dae.projecto.bank.model.Client;
import java.io.IOException;
import java.util.Collection;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Marco
 */
public class ClientController extends HttpServlet {

    private static String VIEWS_PATH = "/WEB-INF/views/";
    @EJB
    private BankSessionLocal controller;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String actionStr = request.getParameter("action");
        String jspView = "";

        if ("edit".equalsIgnoreCase(actionStr)) {
            jspView = doEdit(request, response);
        } else if ("detail".equalsIgnoreCase(actionStr)) {
            jspView = doDetail(request, response);
        } else if ("new".equalsIgnoreCase(actionStr)) {
            jspView = doNew(request, response);
        } else if ("remove".equalsIgnoreCase(actionStr)) {
            jspView = doRemove(request, response);
        } else if ("save".equalsIgnoreCase(actionStr)) {
            jspView = doSave(request, response);
        } else if ("update".equalsIgnoreCase(actionStr)) {
            jspView = doUpdate(request, response);
        } else {
            jspView = doList(request, response);
        }

        request.setAttribute("title", "Clientes");
        request.setAttribute("contextPath", request.getContextPath());

        request.getRequestDispatcher(VIEWS_PATH + jspView).include(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Client Servlet";
    }// </editor-fold>

    private String doDetail(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("clientId"));
        Client client = controller.getClientById(id);

        return doDetail(request, response, client);
    }

    private String doDetail(HttpServletRequest request, HttpServletResponse response, Client client) {
        request.setAttribute("action", "Ficha CLiente");
        request.setAttribute("formMethod", "detail");
        request.setAttribute("editable", "disabled");
        request.setAttribute("client", client);
        request.setAttribute("accounts", client.getAccounts());

        return "ClientDetail.jsp";
    }

    private String doEdit(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("clientId"));
        request.setAttribute("action", "Editar Ficha CLiente");
        request.setAttribute("formMethod", "update");
        request.setAttribute("client", controller.getClientById(id));

        return "ClientDetail.jsp";
    }

    private String doNew(HttpServletRequest request, HttpServletResponse response) {
            Client client = new Client();
        try {
            client.setName(request.getParameter("name"));
        }
        catch(Exception err) { /* silencia a excepção */}
        try {
            client.setNif(request.getParameter("nif"));
        }
        catch(Exception err) { /* silencia a excepção */}
        try {
            client.setAddress(request.getParameter("address"));
        }
        catch(Exception err) { /* silencia a excepção */}
        try {
            client.setTown(request.getParameter("town"));
        }
        catch(Exception err) { /* silencia a excepção */}
        try {
            client.setPhone(request.getParameter("phone"));
        }
        catch(Exception err) { /* silencia a excepção */}
        try {
            client.setEmail(request.getParameter("email"));
        }
        catch(Exception err) { /* silencia a excepção */}
        request.setAttribute("client", client);

        request.setAttribute("action", "Novo Cliente");
        request.setAttribute("formMethod", "save");

        return "ClientDetail.jsp";
    }

    private String doRemove(HttpServletRequest request, HttpServletResponse response) {
        return doList(request, response);
    }

    private String doSave(HttpServletRequest request, HttpServletResponse response) {
        try {
            int agencyCode = Integer.parseInt(request.getParameter("agency"));
            Client client = new Client();
            client.setName(request.getParameter("name"));
            client.setNif(request.getParameter("nif"));
            client.setAddress(request.getParameter("address"));
            client.setTown(request.getParameter("town"));
            client.setPhone(request.getParameter("phone"));
            client.setEmail(request.getParameter("email"));
            controller.createClient(client, agencyCode);

            return doDetail(request, response, client);
        } catch (NumberFormatException ex) {
            request.setAttribute("formError", "Tem de indicar o código do balcão.");

            return doNew(request, response);
        } catch (Exception ex) {
            request.setAttribute("formError","O número de contribuinte já existe.");

            return doNew(request, response);
        }
    }

    private String doUpdate(HttpServletRequest request, HttpServletResponse response) {
        try {
            int id = Integer.parseInt(request.getParameter("clientId"));
            Client client = controller.getClientById(id);
            client.setName(request.getParameter("name"));
            client.setNif(request.getParameter("nif"));
            client.setAddress(request.getParameter("address"));
            client.setTown(request.getParameter("town"));
            client.setPhone(request.getParameter("phone"));
            client.setEmail(request.getParameter("email"));
            controller.updateClient(client);

            return doDetail(request, response);
        } catch (Exception ex) {
            request.setAttribute("formError","O número de contribuinte já existe.");

            return doEdit(request, response);
        }
    }

    private String doList(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("action", "Listagem Clientes");
        Collection<Client> clients = controller.getAllClients();
        request.setAttribute("collection", clients);

        return "ClientList.jsp";
    }
}
